package cn.momoshenchi.medicine.service.impl;

import cn.momoshenchi.medicine.pojo.BaseDoctor;
import cn.momoshenchi.medicine.service.BaseDoctorService;
import cn.momoshenchi.medicine.util.AssertUtil;
import cn.momoshenchi.medicine.vo.Consult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.momoshenchi.medicine.pojo.ConsultAsk;
import cn.momoshenchi.medicine.service.ConsultAskService;
import cn.momoshenchi.medicine.mapper.ConsultAskMapper;
import io.goeasy.GoEasy;
import io.goeasy.publish.GoEasyError;
import io.goeasy.publish.PublishListener;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class ConsultAskServiceImpl extends ServiceImpl<ConsultAskMapper, ConsultAsk>
        implements ConsultAskService
{

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.baseUrl}")
    private String baseUrl;

    @Autowired
    private BaseDoctorService doctorService;

    @Autowired
    private  PublishListener publishListener;

    @Autowired
    private  GoEasy goEasy;

    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"};

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public void consult(Consult consult, MultipartFile[] files) throws IOException
    {
        boolean isFlag = false;
        for (MultipartFile file : files)
        {
            for (String type : IMAGE_TYPE)
            {
                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type))
                {
                    isFlag = true;
                    break;
                }
            }
        }
        AssertUtil.isTrue(!isFlag, "图片格式不正确");
        String doctorId = consult.getDoctorId();
        BaseDoctor baseDoctor = doctorService.getById(doctorId);

        ConsultAsk consultAsk = new ConsultAsk();
        BeanUtils.copyProperties(consult, consultAsk);
        BeanUtils.copyProperties(baseDoctor, consultAsk);

        consultAsk.setDoctorLevelCode(baseDoctor.getLevelCode());
        consultAsk.setDoctorLevelName(baseDoctor.getLevelName());
        consultAsk.setPersonCardType("1");
        consultAsk.setConsultStatus(Byte.parseByte("1"));

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //图片地址使用逗号进行分隔
        StringBuilder url = new StringBuilder();
        for (MultipartFile file : files)
        {
            InputStream inputStream = file.getInputStream();
            String path = "medicine/" + consult.getCreateUserId() + "/" + file.getOriginalFilename();
            url.append(baseUrl)
                    .append("/")
                    .append(path)
                    .append(",");
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。

            ossClient.putObject("gulimail-momoshenchi", path, inputStream);
            inputStream.close();
        }
        ossClient.shutdown();

        consultAsk.setPhotoIds(url.toString());
        AssertUtil.isTrue(!save(consultAsk), "操作失败");
    }

    @Override
    public String upload(MultipartFile[] files) throws IOException
    {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //图片地址使用逗号进行分隔

        StringBuilder url = new StringBuilder();
        Date d=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(d);
        for (MultipartFile file : files)
        {
            InputStream inputStream = file.getInputStream();
            String path = "medicine" + "/" +date+"/" +file.getOriginalFilename();
            url.append(baseUrl).append("/").append(path);
            url.append(",");
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。

            ossClient.putObject("gulimail-momoshenchi", path, inputStream);
            inputStream.close();
        }
        ossClient.shutdown();
        return  url.toString();
    }

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public void consultByImg(Consult consult)
    {
        String doctorId = consult.getDoctorId();
        BaseDoctor baseDoctor = doctorService.getById(doctorId);

        ConsultAsk consultAsk = new ConsultAsk();
        //注意先后顺序
        BeanUtils.copyProperties(consult, consultAsk);
        BeanUtils.copyProperties(baseDoctor, consultAsk);

        consultAsk.setCreateTime(null);
        consultAsk.setDoctorLevelCode(baseDoctor.getLevelCode());
        consultAsk.setDoctorLevelName(baseDoctor.getLevelName());
        consultAsk.setPersonCardType("1");
        consultAsk.setConsultStatus(Byte.parseByte("1"));
        AssertUtil.isTrue(!save(consultAsk), "操作失败");

        // 通过goeasy发送给doctor
        goEasy.publish("doctor_"+doctorId, "新用户提交复诊请求", publishListener);
    }


}




